# coding:utf-8
# from __future__ import unicode_literals
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.conf import settings
from os.path import basename
from os.path import join
import time
from palmgo.models import city_manage,updown_cars,updown_cars_detail
from log_write import log_class

yesterday=time.strftime('%Y%m%d',time.localtime(time.time()))
timeArray = time.strptime(yesterday, "%Y%m%d")
time_unix=int(time.mktime(timeArray))


log = log_class()

city_m = {}
for i in city_manage.objects.all():
	city_m.setdefault(i.citycode, i.cityname)  ##数据库中 citycode与cityname对应关系字典

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from captcha.fields import CaptchaField
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url

from django import forms

class CaptchaTestForm(forms.Form):
	captcha = CaptchaField()


def login_user(request):
	# captcha = CaptchaField()
	# hashkey = CaptchaStore.generate_key()
	# imgage_url = captcha_image_url(hashkey)
	# print captcha
	# print hashkey
	# print imgage_url

	form=CaptchaTestForm(request.POST)
	# print form.as_ul()

	# print  request.POST
		# print "验证码不能为空"

	# print locals()


	if request.GET.get('newsn') == '1':
		csn = CaptchaStore.generate_key()
		cimageurl = captcha_image_url(csn)
		return HttpResponse(cimageurl)

	page = request.GET.get('next')
	if request.method == 'POST':

		if form.is_valid():
			# print 1
			human=True
		else:
			return render_to_response('login.html', {'form':form,'login_err': u'验证码错误'})

		username = request.POST.get('username', '')
		password = request.POST.get('password', '')
		user = authenticate(username=username, password=password)
		if user is not None:
			# the password verified for the user
			if user.is_active:
				print("User is valid, active and authenticated")
				login(request, user)
				if not page:
					log.info('Module:view.login_user 登录用户:%s 跳转页面:%s' % (user, 'index'))
					return HttpResponseRedirect('/index')
				else:
					log.info('Module:view.login_user 登录用户:%s 跳转页面:%s' % (user, page))
					return HttpResponseRedirect(page)
			else:
				log.info('Module:view.login_user 登录用户:%s 没有激活' % (user))
				return render_to_response('login.html', {'form':form,'login_err': u'err user is no active'})
		else:
			# the authentication system was unable to verify the username and password
			log.info('Module:view.login_user 登录用户 密码不正确')
			return render_to_response('login.html', {'form':form,'login_err': u'用户名 或 密码 错误'})

	return render_to_response('login.html',locals())


def logout_user(request):
	logout(request)

	return HttpResponseRedirect('/login')


from django.contrib.auth.decorators import login_required,permission_required
from summary import summary

from sqlserver import mssql_session


@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.index')
def index(request):

	# if request.user.has_perm('palmgo.index'):
	L=list(request.user.get_all_permissions())
	# print L
	L.sort(reverse=True)
	# print L
		# print request.user.has_perm('palmgo')

	mss=mssql_session()
	commit_mem=mss.vpx_mem()
	print commit_mem
	# print mss.vpx_storage()

	total_vps,total_host,storage_vps,cluster_host=mss.vcenter_total()
	print total_vps,total_host,storage_vps,cluster_host

	free_space,total_space,commit_storage,uncommit_storage,unshare_storage=mss.storage_space()
	# # #
	s = summary()
	cputotal, cpu_usage, cpu_usage_percentage = s.hypervisors_cpu()

	memtotal, memusage, mem_usage_percentage = s.hypervisors_mem()

	# print commit_mem,mem_usage_percentage,commit_mem/ (memtotal/ 1024 /1024)

	cache_key="inboud_traffic"
	inboud=cache.get(cache_key,None)
	if not inboud:
		taxi, keyun, huoyun, ugc = s.inboud_traffic()

		inboud = {'taxi': taxi, 'keyun': keyun, 'huoyun': huoyun, 'ugc': ugc}
		cache.set(cache_key,inboud,300)

	for i in inboud:
		if not inboud[i]:  ##如果没有数据
			inboud[i] = 0


	log.debug('Module:view.index 主页流量分布:(taxi:%d,keyun:%d,huoyun:%d,ugc:%d)' % (inboud['taxi'], inboud['keyun'], inboud['huoyun'], inboud['ugc']))



	nas_size=general.objects.filter(date=time_unix, type='NAS_Size').values('note')


	if nas_size:
		nas=eval(str(nas_size))
		nas= eval(nas[0]['note'])
		print nas,type(nas)
		# nas_size= nas[0]['note']
		nas_total=nas['total_size']
		nas_list=[{'value':nas['gps_size'],'name':'GPS'},
				  {'value':nas['fcdrhti_size'],'name':'FCD融合多车'},
				  {'value':nas_total - nas['gps_size'] - nas['fcdrhti_size'],'name':'剩余空间'}]

	nas_title=[u"GPS",u"FCD融合多车",u"剩余空间"]
	print nas_list
	print nas_title
	print nas_total,type(nas_total)



	return render_to_response("index.html", {'cpu_usage': '%.2f' % (cpu_usage_percentage * 100),\
											 'mem_usage': '%.2f' % (mem_usage_percentage * 100), \
											 'cputotal': '%.2f' % (cputotal / 1024 / 1024 / 1024),\
											 'cpuusage': '%.2f' % (cpu_usage / 1024 / 1024 / 1024),\
											 'memtotal': '%.2f' % (memtotal / 1024 / 1024 / 1024), \
											 'memusage': '%.2f' % (memusage / 1024 / 1024 / 1024),\
											 'mem_commit_usage': '%.2f' % (commit_mem/ (memtotal/ 1024 /1024) * 100),\
											 'mem_commit':  '%.2f' % (commit_mem / 1024 ),\
											 'keyun': '%.2f' % (inboud['keyun'] / 1024 / 1024),\
											 'huoyun': '%.2f' % (inboud['huoyun'] / 1024 / 1024), \
											 'taxi': '%.2f' % (inboud['taxi'] / 1024 / 1024),
											 'ugc': '%.2f' % (inboud['ugc'] / 1024 / 1024),
											 'total_vps':total_vps,'total_host':total_host,'cluster_host':cluster_host,
											 'storage_vps':storage_vps,'commit_storage':commit_storage,\
											 'uncommit_storage':uncommit_storage,'unshare_storage':unshare_storage,\
											 'free_space':free_space,'total_space':total_space,\
											 'nas_list':nas_list,'nas_title':nas_title,'nas_total':nas_total,\
											 'user':request.user,'perms':list(request.user.get_all_permissions()),
											 })


import mysql_data, time, json, datetime

@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.interface')
def totle_interface(request):  ##接口获取频次
	ltime = time.localtime(time.time())
	date = time.strftime("%Y-%m-%d %H:%M", ltime)
	# date=datetime.datetime.now()
	kehu = 'SGDTIPLUS16Q211T2'

	x_list = ['0:0']
	y_list = [0]
	select_16q2 = ""
	select_15q4 = ''
	select_dti = ''

	if 'date' in request.GET and 'kehu' in request.GET:
		get_date = request.GET['date']
		get_kehu = request.GET['kehu']
		get_version = request.GET['version']

		if get_date and get_kehu:  ##使用默认 表单内容
			date = get_date
			kehu = get_kehu

		if get_version == '16Q2':
			select_16q2 = "selected="
			d = mysql_data.session(db='siwei16Q2rtti')
		elif get_version == '15Q4':
			select_15q4 = "selected="
			d = mysql_data.session(db='siwei15Q4rtti')
		else:
			select_dti = "selected="
			d = mysql_data.session(db='rtti')

		d_tmp = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M")
		dd_tmp = int(time.mktime(d_tmp.timetuple()))

		start = int(str(dd_tmp) + "000")

		end = start + 7200000

		dd = d.data(start, end, kehu)
		dd = list(dd)
		start = int(str(start)[0:-3])
		end = int(str(end)[0:-3])
		data_dict = {}
		x_list = []
		y_list = []

		while 1:
			list_init = []
			start = start + 300
			ltime = time.localtime(start)
			timeStr = time.strftime("%H:%M", ltime)
			s = 0
			for i in dd:  ##dd列表中是 每个请求的 UNIX时间
				i = int(i[0])
				if start > i and i > start - 300:  ## 每个5分钟的请求数
					s = s + 1

			x_list.append(timeStr)
			y_list.append(s)
			if start == end:
				break

	kehu_title = kehu + u'  获取记录'

	return render_to_response("total_interface.html",
							  {'x': json.dumps(x_list), 'y': json.dumps(y_list), 'date': date, 'kehu': kehu, \
							   'kehu_title': json.dumps(kehu_title), 'select_15q4': select_15q4,
							   'select_16q2': select_16q2, \
							   'select_dti': select_dti,'perms':list(request.user.get_all_permissions())})


import csvfile

@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.interface')
def download_interface(request):
	ltime = time.localtime(time.time())
	b_date = time.strftime("%Y-%m-%d %H:%M", ltime)
	e_date = time.strftime("%Y-%m-%d %H:%M", ltime)
	# date=datetime.datetime.now()
	kehu = 'SGDTIPLUS16Q211T2'
	_datalist = []
	field = ["客户名称", "访问时间", "城市名", "业务名称", "数据量", "数据文件名称", "来源IP"]
	csvfilename = '#'
	select_16q2 = ''
	select_15q4 = ""
	select_dti = ''

	if 'b_date' in request.GET and 'e_date' in request.GET and 'kehu' in request.GET:
		get_b_date = request.GET['b_date']
		get_e_date = request.GET['e_date']
		get_kehu = request.GET['kehu']
		get_version = request.GET['version']
		if get_b_date and get_kehu and get_e_date:  ##使用默认 表单内容
			b_date = get_b_date
			e_date = get_e_date
			kehu = get_kehu

			b_tmp = datetime.datetime.strptime(b_date, "%Y-%m-%d %H:%M")
			bb_tmp = int(time.mktime(b_tmp.timetuple()))

			start = int(str(bb_tmp) + "000")

			e_tmp = datetime.datetime.strptime(e_date, "%Y-%m-%d %H:%M")
			ee_tmp = int(time.mktime(e_tmp.timetuple()))

			end = int(str(ee_tmp) + "000")

			if get_version == '16Q2':
				select_16q2 = "selected="
				s = mysql_data.session(db='siwei16Q2rtti')
			elif get_version == '15Q4':
				select_15q4 = "selected="
				s = mysql_data.session(db='siwei15Q4rtti')
			else:
				select_dti = "selected="
				s = mysql_data.session(db='rtti')

			_data = s.all_data(start, end, kehu)

			#
			# _city_m={}
			# for i in city_manage.objects.all():
			#     _city_m.setdefault(i.citycode,i.cityname) ##数据库中 citycode与cityname对应关系字典

			for row in _data:
				row = list(row)
				ltime = time.localtime(int(row[1]))
				row[1] = time.strftime("%Y-%m-%d %H:%M:%S", ltime)
				row[2] = city_m[row[2]]
				_datalist.append(row)

			csvfilename = kehu + '_' + str(time.time()) + '.csv'
			csvfile.csvfile(csvfilename, _datalist)  ##生成 下载文件

	return render_to_response('download_interface.html',
							  {'csvfilename': csvfilename, 'b_date': b_date, 'e_date': e_date, 'kehu': kehu, \
							   'table_header': field, 'access_data': _datalist, 'select_15q4': select_15q4,
							   'select_16q2': select_16q2, \
							   'select_dti': select_dti,'perms':list(request.user.get_all_permissions())})


##接口获取－接口获取频次城市

import city_interface_class
import Queue, multiprocessing

@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.interface')
def city_interface(request):  ##

	# ltime=time.localtime(time.time())
	# date=time.strftime("%Y-%m-%d", ltime)

	date = str(datetime.date.today())

	kehu = 'SOUGOUCJ16Q211T0'


	x_list = ['0:0']
	y_list = [0]

	item = [
		{'title': '初始化', 'data': [{'data': [0, 0]}, {'data': [0, 0]}, ]},  ##data列表中每 一个 data字典都是 这个时间段内 所有城市每5分钟的次数
		{'title': '初始化', 'data': [{'data': [0, 0]}, {'data': [0, 0]}, ]}
	]
	firstdata = [
		{'name': '初始化', 'data': [0, 0]},
	]
	selected = {}
	first_text = "初始化"
	select_16q2 = ""
	select_15q4 = ''
	select_dti = ''

	if 'date' in request.GET and 'kehu' in request.GET:
		get_date = request.GET['date']
		get_kehu = request.GET['kehu']
		get_version = request.GET['version']
		if get_date and get_kehu:
			if str(get_date) == date:  ##判断  输入日期 是否在当天
				d_tmp = datetime.datetime.strptime(date, "%Y-%m-%d")
				kehu = get_kehu
			else:
				date = get_date
				kehu = get_kehu
				d_tmp = datetime.datetime.strptime(str(date), "%Y-%m-%d")  ##不是当天，用输入的日期

		else:  ##没有输入内容，使用默认 表单内容
			d_tmp = datetime.datetime.strptime(date, "%Y-%m-%d")

		dd_tmp = int(time.mktime(d_tmp.timetuple()))

		if get_version == '16Q2':
			select_16q2 = "selected="
			d = mysql_data.session(db='siwei16Q2rtti')
		elif get_version == '15Q4':
			select_15q4 = "selected="
			d = mysql_data.session(db='siwei15Q4rtti')
		else:
			select_dti = 'selected='
			d = mysql_data.session(db='rtti')

		start = int(str(dd_tmp) + "000")

		end = start + 86400000  ##一天 24小时

		dd = d.city_data(start, end, kehu)
		dd = list(dd)
		start = int(str(start)[0:-3])
		end = int(str(end)[0:-3])

		time_line = []
		for i in xrange(1, 25):
			time_line.append(start + i * 3600)  ##时间列表

		# city_m={}
		# for i in city_manage.objects.all():
		#     city_m.setdefault(i.citycode,i.cityname) ##数据库中 citycode与cityname对应关系字典

		city_list = []  ##访问日志中提取出来的 列表citycode
		for i in dd:
			city_list.append(i[0])
		city_list = list(set(city_list))

		x_list = []  ##图例中城市列表
		for i in city_list:
			x_list.append(city_m[i])

		selected = {}  ##城市是否选择  选中
		for i in x_list:
			selected.setdefault(i, 0)

		ltime = time.localtime(time_line[0])
		first_text = time.strftime("%Y-%m-%d %H", ltime)  ##第一页中 标题

		q = Queue.Queue()
		threadpool = []
		firstdata = []
		item = []
		pool = multiprocessing.Pool(processes=2)

		for i in time_line:

			if i - 3600 == start:
				pool.apply_async(city_interface_class.first(city_list, dd, i, city_m, q, firstdata))

			else:
				pool.apply_async(city_interface_class.item_data(city_list, dd, i, q, item))

		pool.close()
		pool.join()

		result = []

		while not q.empty():
			result.append(q.get())
		for i in request:
			if i[0] == "firest":
				firstdata = i[1]
			if i[0] == "item":
				item = i[1]
	return render_to_response("city_interface.html",
							  {'firstdata': firstdata, 'item': item, 'x': x_list, 'selected': selected, 'date': date,
							   'kehu': kehu, \
							   'first_text': first_text, 'select_15q4': select_15q4, 'select_16q2': select_16q2,
							   'select_dti': select_dti,'perms':list(request.user.get_all_permissions())})
	# return render_to_response("city_interface.html")



from palmgo.models import backupfile

@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.source_total')
def backupfile_show(request):
	# rs = redis_data.redis_data()
	# source_list = rs.source_key()

	startdate = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60 * 7))  ##一周前

	enddate = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60))

	filed = ['日期','城市', '数据源',  '备份文件大小(MB)']

	if  'scope' in request.GET:
		date_range = request.GET['scope']
		date_range = str(date_range)
		startdate, enddate = date_range.split(' ')[0], date_range.split(' ')[-1]

		# source = request.GET['source']
		#
		# for n in xrange(len(source_list)):
		# 	i = source_list[n]
		#
		# 	if unicode(i['source'], 'gbk') == source:  ##是否在页面上选择过
		# 		source_list[n]['select'] = "selected="

				# city_m={}
			#
		# for i in city_manage.objects.all():
		#     city_m.setdefault(i.citycode,i.cityname) ##数据库中 citycode与cityname对应关系字典


		start = datetime.datetime.strptime(startdate, "%Y-%m-%d")
		end = datetime.datetime.strptime(enddate, "%Y-%m-%d")

		start = time.mktime(start.timetuple())
		end = time.mktime(end.timetuple()) + 86400

		fault = fault_totla_output.fault_total_output()  ##生成日期序列
		date_list = fault.init_datelist(int(end)+86400, int(start))

		date_list = map(lambda x: time.strftime("%Y-%m-%d", time.localtime(x)), date_list)

		# print backupfile.objects.filter(date__range=(start, end))
		# print len(backupfile.objects.annotate(Count('source'))),backupfile.objects.annotate(Count('source'))

		b = backupfile.objects.distinct().values("source")  ## 数据源去重 字典

		# print len(b),b

		source_list=[i['source'] for i in b]

		print source_list
		# source_list=[i for i in b i['source']]

		gps_m = []
		backupfile_view=[]

		data=backupfile.objects.filter(date__range=(start, end)).values('date','source','filesize')

		for s in b:
			tmp_gps_dict={}
			s=s['source']

			_tmp_list=[]

			for t in xrange(int(start),int(end)+86400,86400):
				v=0
				for d in data:
					if d['date'] == t and s == d['source']:
						_tmp_list.append(d['filesize'])
						v=1

				if not v:   #如果 某一天 数据库没有数据   补0
					_tmp_list.append(0)


			tmp_gps_dict.setdefault('source',s)
			tmp_gps_dict.setdefault('datalist',_tmp_list)
			# print s,_tmp_list

			backupfile_view.append(tmp_gps_dict)

		# print backupfile_view
		field=[' ']+date_list

		_data=[]
		for i in backupfile_view:
			_data.append([i['source']]+i['datalist'])

		csvfilename = 'backupfile_'+str(time.time()) + '.csv'
		csvfile.csvfile_view( csvfilename,_data,field)


		for i in backupfile.objects.filter(date__range=(start, end)):
			gps_m.append(
				[time.strftime("%Y-%m-%d", time.localtime(i.date)), i.source, city_m[i.citycode], i.filesize])  ##形成数据表的 城市名
		# print gps_m


	else:
		return render_to_response('backupfile_show.html', {'table_header': filed, 'startdate': startdate, 'enddate': enddate, \
													   'perms':list(request.user.get_all_permissions())})
	# print date_list
	date_list=[i for i in date_list if time.mktime(datetime.datetime.strptime(i,"%Y-%m-%d").timetuple()) < time.mktime(datetime.date.today().timetuple()) ]
	# print date_list
		# print gps_data_list
	return render_to_response('backupfile_show.html',
							  {'table_header': filed, 'startdate': startdate, 'enddate': enddate, \
							   'backupfile_view': backupfile_view, 'data': gps_m,'csvfilename':csvfilename, \
							   'date_list': date_list, 'source_list': source_list, \
							   'perms': list(request.user.get_all_permissions())})







from palmgo.models import gps_data

@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.source_total')
def taxi_table(request):
	rs = redis_data.redis_data()
	source_list = rs.source_key()

	startdate = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60 * 7))  ##一周前

	enddate = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60))

	filed = ['日期', '数据源', '车辆数', 'gps总量', '重复率', '中断时间']

	if 'source' in request.GET and 'scope' in request.GET:
		date_range = request.GET['scope']
		date_range = str(date_range)
		startdate, enddate = date_range.split(' ')[0], date_range.split(' ')[-1]

		source = request.GET['source']

		for n in xrange(len(source_list)):
			i = source_list[n]

			if unicode(i['source'], 'gbk') == source:  ##是否在页面上选择过
				source_list[n]['select'] = "selected="

				# city_m={}
			#
		# for i in city_manage.objects.all():
		#     city_m.setdefault(i.citycode,i.cityname) ##数据库中 citycode与cityname对应关系字典

		gps_data_list = []
		cars_list = []
		gps_m = []
		tmp_gps_dict={}

		start = datetime.datetime.strptime(startdate, "%Y-%m-%d")
		end = datetime.datetime.strptime(enddate, "%Y-%m-%d")

		start = time.mktime(start.timetuple())
		end = time.mktime(end.timetuple()) + 86400

		fault = fault_totla_output.fault_total_output()  ##生成日期序列
		date_list = fault.init_datelist(int(end), int(start))

		date_list = map(lambda x: time.strftime("%Y-%m-%d", time.localtime(x)), date_list)

		for i in gps_data.objects.filter(date__range=(start, end), source=source):
			gps_m.append(
				[time.strftime("%Y-%m-%d", time.localtime(i.date)), i.source, i.cars, i.gps_data, '%.2f' % (i.repeats),
				 i.interrupt])  ##形成数据表的 城市名
			gps_data_list.append(int(i.gps_data) / 10000)
			cars_list.append(int(i.cars))

			tmp_gps_dict.setdefault(i.date,(i.gps_data/10000,i.cars)) ## 防止 某天的数据在数据库中没有，日期列表与 数据列表 长度不同

	else:
		return render_to_response('taxi_table.html', {'table_header': filed, 'startdate': startdate, 'enddate': enddate, \
													  'source_list': source_list, 'perms':list(request.user.get_all_permissions())})
	# print date_list
	date_list=[i for i in date_list if time.mktime(datetime.datetime.strptime(i,"%Y-%m-%d").timetuple()) < time.mktime(datetime.date.today().timetuple()) ]
	# print date_list  如果选中 当前日期，由于没有当天的数据，要去掉当天日期 以及后面的日期

	# print len(gps_data_list),len(date_list)
	# print gps_data_list
	if not (len(gps_data_list) == len(date_list)):  ##如果日期列表与数据列表 长度不同
		gps_data_list=[]
		cars_list=[]
		for d in xrange(len(date_list)):

			d = datetime.datetime.strptime(date_list[d],"%Y-%m-%d")
			# print d
			if tmp_gps_dict.has_key(int(time.mktime(d.timetuple()))):
				# print tmp_gps_dict[int(time.mktime(d.timetuple()))]
				gps_data_list.append(int(tmp_gps_dict[int(time.mktime(d.timetuple()))][0]))
				cars_list.append(int(tmp_gps_dict[int(time.mktime(d.timetuple()))][1]))
			else:
				gps_data_list.append(0)
				cars_list.append(0)

		# print gps_data_list
	return render_to_response('taxi_table.html', {'table_header': filed, 'startdate': startdate, 'enddate': enddate, \
												  'source_list': source_list, 'source': source, 'data': gps_m,
												  'date_list': date_list, \
												  'gps_data_list': gps_data_list, 'car_list': cars_list,\
												  'perms':list(request.user.get_all_permissions())})


import excelfile

@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.source_total')
def taxi_show(request):
	date = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60))
	d = datetime.datetime.strptime(date, "%Y-%m-%d")
	filter_time = time.mktime(d.timetuple())  ##默认昨天

	if 'date' in request.GET:
		date = request.GET['date']
		d = datetime.datetime.strptime(date, "%Y-%m-%d")
		filter_time = time.mktime(d.timetuple())

	# city_m={}
	filed = ['城市', '数据源', '车辆数', 'gps总量', '重复率(%)', '中断时间']
	# for i in city_manage.objects.all():
	#     city_m.setdefault(i.citycode,i.cityname) ##数据库中 citycode与cityname对应关系字典

	gps_data_list = []
	cars_list = []

	gps_m = []
	for i in gps_data.objects.all().filter(date=int(filter_time)):
		gps_m.append([city_m[str(int(i.citycode))], i.source, i.cars, i.gps_data, '%.2f' % (i.repeats * 100),
					  i.interrupt])  ##形成数据表的 城市名
		gps_data_list.append({'name': i.source, 'value': int(i.gps_data) / 100000.0})  ##GPS总量图中的 数据源名称
		cars_list.append({'name': i.source, 'value': '%.2f' % (int(i.cars) / 10000.0)})

	_dir = settings.MEDIA_ROOT  ##默认静态文件位置

	csvfile.create_file(join(_dir, 'tmp'), date + '.xlsx')
	excel_file = join(_dir, 'tmp', date + '.xlsx')
	headings = [u'城市', u'数据源', u'车辆数', u'GPS总量', u'重复率(%)', u'中断时间']
	excel = excelfile.excel_file(excel_file)
	excel.main(headings, gps_m)

	return render_to_response('taxi_show.html', {'date': date, 'table_header': filed, 'access_data': gps_m,
												 'gps_data_list': gps_data_list, \
												 'cars_list': cars_list, 'excel_file': excel_file,\
												 'perms':list(request.user.get_all_permissions())})


from django.core.cache import cache
import redis

@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.source_total')
def huoyun_show(request):
	mc = redis.Redis(host='172.16.30.45', port=6379, db=0)

	cache_key="huoyun_show"
	_datadict=cache.get(cache_key,None)
	if not _datadict:
		if mc.exists('huoyun_dict'):
			_data = mc.get('huoyun_dict')
			_datadict = eval(_data)
		else:
			print 'no data'
			_data = []
			_datadict = {}
			return render_to_response('huoyun_show.html', {'list': _data, 'no_data': '当前无数据'})

		cache.set(cache_key,_datadict,300)

	list1 = _datadict['gps_list']  ##只有10万个点
	time_str = _datadict['time']
	timeid = _datadict['timeid']
	source = _datadict['source']
	cars = _datadict['cars']
	data_total = _datadict['data_total']
	# list1=[]
	print time_str, timeid, source, cars, data_total

	return render_to_response('huoyun_show.html',
							  {'list': list1, 'time_str': time_str, 'timeid': timeid, 'source': source, 'cars': cars, \
							   'data_total': data_total,\
							   'perms':list(request.user.get_all_permissions())})
@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.source_total')
def keyun_show(request):
	mc = redis.Redis(host='172.16.30.45', port=6379, db=0)

	if mc.exists('keyun_dict'):
		_data = mc.get('keyun_dict')
	else:
		print 'no data'
		list1 = []
		return render_to_response('keyun_show.html', {'list': list1, 'no_data': '当前无数据'})

	_datadict = eval(_data)
	list1 = _datadict['gps_list']  ##只有10万个点
	time_str = _datadict['time']
	timeid = _datadict['timeid']
	source = _datadict['source']
	cars = _datadict['cars']
	data_total = _datadict['data_total']
	# list1=[]
	print time_str, timeid, source, cars, data_total

	return render_to_response('keyun_show.html',
							  {'list': list1, 'time_str': time_str, 'timeid': timeid, 'source': source, 'cars': cars, \
							   'data_total': data_total,\
							   'perms':list(request.user.get_all_permissions())})
@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.source_total')
def source_show(request):
	rs = redis_data.redis_data()
	_datadict = rs.point_source('huoyun_baidu')
	# _datadict=eval(_datadict)
	list_huoyun = eval(_datadict)

	_datadict = rs.point_source('keyun_baidu')
	list_keyun=eval(_datadict)


	list_taxi = []
	for i in [u'常州', u'金银建', u'重庆', u'深圳',u'烟台']:
		_datadict = rs.point_source(i)
		# print _datadict
		_datadict = eval(_datadict)
		list_tmp = _datadict['gps_list']
		list_taxi = list_taxi + list_tmp

	return render_to_response('source_show.html', {'list_taxi': list_taxi, 'list_huoyun': list_huoyun,'list_keyun':list_keyun,\
												   'perms':list(request.user.get_all_permissions())})

@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.source_total')
def source_show_pic(request):
	pic_dir=join(settings.MEDIA_ROOT,'tmp','source_show.png')
	print pic_dir

	return render_to_response('source_show_pic.html', {'pic_dir': pic_dir,\
												   'perms':list(request.user.get_all_permissions())})

def source_show_perm(request):
	rs = redis_data.redis_data()
	_datadict = rs.point_source('huoyun_baidu')
	# _datadict=eval(_datadict)
	list_huoyun = eval(_datadict)

	_datadict = rs.point_source('keyun_baidu')
	list_keyun=eval(_datadict)


	list_taxi = []
	for i in [u'常州', u'金银建', u'重庆', u'深圳',u'烟台',u'途锐',u'杭州',u'南京',u'长沙',u'福州']:
		_datadict = rs.point_source(i)
		# print _datadict
		_datadict = eval(_datadict)
		list_tmp = _datadict['gps_list']
		list_taxi = list_taxi + list_tmp

	return render_to_response('source_show_perm.html', {'list_taxi': list_taxi, 'list_huoyun': list_huoyun,'list_keyun':list_keyun,\
												   'perms':list(request.user.get_all_permissions())})



@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.source_total')
def taxi_all_show(request):
	rs = redis_data.redis_data()
	# _datadict = rs.point_source('huoyun_baidu')
	# # _datadict=eval(_datadict)
	# list_huoyun = eval(_datadict)
	#
	# _datadict = rs.point_source('keyun_baidu')
	# list_keyun=eval(_datadict)
	#

	list_taxi = []
	for i in [u'常州', u'金银建', u'重庆', u'深圳',u'烟台',u'奇华',u'南京',u'长沙',u'东莞',u'烟台',u'瑞明,',\
			u'佛山',u'途锐',u'沈阳',u'西宁',u'乌鲁木齐',u'珠海',u'贵阳',u'武汉',u'海口',u'深圳',u'杭州',u'福州',u'成都']:
		try:
			_datadict = rs.point_source(i)
			# print _datadict
			_datadict = eval(_datadict)
			list_tmp = _datadict['gps_list']
			# print i
			list_taxi = list_taxi + list_tmp
		except Exception as e:
			print str(e)+i


	return render_to_response('taxi_all_show.html', {'list_taxi': list_taxi,\
												   'perms':list(request.user.get_all_permissions())})




import redis_data

@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.source_total')
def cover(request):
	rs = redis_data.redis_data()
	source_list = rs.source_key()

	if 'source' in request.GET:
		source = request.GET['source']
		_datadict = rs.point_source(source)


		for n in xrange(len(source_list)):
			i = source_list[n]

			if unicode(i['source'], 'gbk') == source:  ##是否在页面上选择过
				source_list[n]['select'] = "selected="

		# _city_m={}
		# for i in city_manage.objects.all():
		#     _city_m.setdefault(i.citycode,i.cityname) ##数据库中 citycode与cityname对应关系字典
		#

		if _datadict:  # 如果redis里有这个 数据源的KEY
			if isinstance(_datadict,str):
				_datadict = eval(_datadict)

			list1 = _datadict['gps_list']
			time_str = _datadict['time']

			timeid = _datadict['timeid']
			source = _datadict['source']
			cars = _datadict['cars']
			data_total = _datadict['data_total']
			# print _datadict['citycode']
			cityname = city_m[_datadict['citycode']]
			if data_total ==0 or cars==0:  ## 没有数据源timeid的数据
				interval=0
			else:
				interval=300/(data_total/cars)
		else:

			return render_to_response('cover.html', {'source_list': source_list,'perms':list(request.user.get_all_permissions())})

	else:
		return render_to_response('cover.html', {'source_list': source_list,'perms':list(request.user.get_all_permissions())})

	del _datadict
	return render_to_response('cover.html',
							  {'list': list1, 'time_str': time_str, 'timeid': timeid, 'source': source, 'cars': cars, \
							   'data_total': data_total, 'cityname': cityname, 'source_list': source_list,'interval':interval,\
							   'perms':list(request.user.get_all_permissions())})

@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.source_total')
def source_hot(request):
	rs = redis_data.redis_data()
	source_list = rs.source_key()

	if 'source' in request.GET:
		source = request.GET['source']

		s = source + 'rl'
		print s
		_datadict = rs.point_source(s)

		for n in xrange(len(source_list)):
			i = source_list[n]

			if unicode(i['source'], 'gbk') == source:  ##是否在页面上选择过
				source_list[n]['select'] = "selected="

		# _city_m={}
		# for i in city_manage.objects.all():
		#     _city_m.setdefault(i.citycode,i.cityname) ##数据库中 citycode与cityname对应关系字典

		if _datadict:  # 如果redis里有这个 数据源的KEY
			if isinstance(_datadict,str):
				_datadict = eval(_datadict)


			list1 = _datadict['gps_list']
			time_str = _datadict['time']
			timeid = _datadict['timeid']
			source = _datadict['source']
			cars = _datadict['cars']
			data_total = _datadict['data_total']
			# print _datadict['citycode']
			cityname = city_m[_datadict['citycode']]

			c = city_manage.objects.get(cityname=cityname)
			coordinate = c.coordinates  ##经纬度

			print source
			if source in [u"城际货运",u"深圳2"] :
				chengji=1
				coordinate="109.531398,35.897445"
			else:
				chengji=0

			if not list1:
					return render_to_response('source_hot.html',
							  {"coordinate": coordinate,'time_str': time_str, 'timeid': timeid,
							   'source': source, 'cars': cars,\
							   'data_total': data_total, 'cityname': cityname, 'source_list': source_list,\
							   'perms':list(request.user.get_all_permissions())})

		else:
			return render_to_response('source_hot.html', {'source_list': source_list,'perms':list(request.user.get_all_permissions())})

	else:
		return render_to_response('source_hot.html', {'source_list': source_list,'perms':list(request.user.get_all_permissions())})

	del _datadict
	return render_to_response('source_hot.html',
							  {"coordinate": coordinate, 'list': list1, 'time_str': time_str, 'timeid': timeid,
							   'source': source, 'cars': cars,'interval':300/(data_total/cars), 'chengji':chengji, \
							   'data_total': data_total, 'cityname': cityname, 'source_list': source_list,\
							   'perms':list(request.user.get_all_permissions())})



@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.source_total')
def updowncars(request):
	date = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60))
	d = datetime.datetime.strptime(date, "%Y-%m-%d")
	filter_time = time.mktime(d.timetuple())  ##默认昨天

	if 'date' in request.GET:
		date = request.GET['date']
		d = datetime.datetime.strptime(date, "%Y-%m-%d")
		filter_time = time.mktime(d.timetuple())



	_dir = settings.MEDIA_ROOT  ##默认静态文件位置

    ##总览表
	updown_file="updowncars_"+date + '.csv'
	# updown_dir_file=join(_dir, 'tmp',updown_file)
	csvfile.create_file(join(_dir, 'tmp'),updown_file)

	updown_data=updown_cars.objects.filter(date=filter_time).values_list()

	data=csvfile.updowncars_csv(updown_data,join(_dir, 'tmp',updown_file))

	data=[i for i in data if i[u"切换车辆总数"] != 0]


	for i in range(1,len(data) / 5 + 1):
		for n in range((i-1)*5,i*5):
			data[n]['center']=[str(10+(n%5)*20)+'%', str(i*20)+'%']
		# print 'ok'
	if n < len(data):
		for n in range(n+1,len(data)):
			data[n]['center']=[str(10+(n%5)*20)+'%', str((i+1)*20)+'%']

	del i,n
	
	##详细表
	updown_detail_file="updowncars_detail_"+date + '.xlsx'

	d = updown_cars_detail.objects.filter(date=filter_time).values_list("source", "carid", "change_nums")
	#
	data_dict = {}
	for i in d:
		_tmp_list=[]
		if data_dict.has_key(i[0]):
			data_dict[i[0]].append([i[1],i[2]])
		else:
			_tmp_list.append([i[1],i[2]])
			data_dict.setdefault(i[0],_tmp_list)



	e=excelfile.excel_file(join(_dir, 'tmp',updown_detail_file))
	e.updown_detail(data_dict)
	del d
	del data_dict

	return render_to_response('updowncars.html', {'date': date,'data':data, 'updown_file': updown_file,'updown_detail_file':updown_detail_file,\
												 'perms':list(request.user.get_all_permissions())})




import mail_send
from palmgo.models import fusion_yc, rh_yc, general
import ribao_create


@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.ribao')
def ribao(request):
	date = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60))
	# print date
	# d = datetime.datetime.strptime(date,"%Y-%m-%d")
	# print d
	# d= time.mktime(d.timetuple())
	# print d

	if 'date' in request.GET:
		date = request.GET['date']

	note = ""
	if 'note' in request.GET:
		date = request.GET['date_note']
		d = datetime.datetime.strptime(date, "%Y-%m-%d")
		d = time.mktime(d.timetuple())

		note = request.GET['note']
		print note
		try:
			p = general.objects.get(date=d, type='备注说明')
		except general.DoesNotExist:
			general.objects.create(date=d, note=note, type='备注说明')
		else:
			p.note = note
			p.save()

	d = datetime.datetime.strptime(date, "%Y-%m-%d")
	filter_time = time.mktime(d.timetuple())  ##默认昨天

	table_header = [u'服务器IP', u'城市', u'延迟数', u'延迟时间段', u'不存在个数', u'不存在时间段', u'版本']
	table_general = [u'日期', u'类型', u'结果']
	data = fusion_yc.objects.filter(date=filter_time)

	fusion_table_list = []
	for i in data:
		# print  i.delay_str,len(str(i.delay_str).split(','))

		if len(str(i.delay_str).split(',')) > 5:
			d_str=','.join(str(i.delay_str).split(',')[0:4])+u'等'
		else:
			d_str=','.join(str(i.delay_str).split(',')[0:4])

		if len(str(i.noexist_str).split(',')[0:4]) > 5:
			no_str=','.join(str(i.noexist_str).split(',')[0:4])+u'等'
		else:
			no_str=','.join(str(i.noexist_str).split(',')[0:4])

		_list=[i.host, city_m[i.citycode], i.delay, d_str, i.noexist,no_str, i.version]
		fusion_table_list.append(_list)

	# print fusion_table_list

	_dir = settings.MEDIA_ROOT  ##默认静态文件位置
	csvfile.create_file(join(_dir, 'tmp'), date + '.xlsx')
	excel_file = join(_dir, 'tmp', 'fusion_' + date + '.xlsx')

	e = excelfile.excel_file(excel_file)
	e.main_rh_fuion(table_header, data, city_m)

	data = rh_yc.objects.filter(date=filter_time)
	rh_table_list = []
	for i in data:
		if len(str(i.delay_str).split(',')) > 5:
			d_str=','.join(str(i.delay_str).split(',')[0:4])+u'等'
		else:
			d_str=','.join(str(i.delay_str).split(',')[0:4])

		if len(str(i.noexist_str).split(',')[0:4]) > 5:
			no_str=','.join(str(i.noexist_str).split(',')[0:4])+u'等'
		else:
			no_str=','.join(str(i.noexist_str).split(',')[0:4])

		_list=[i.host, city_m[i.citycode], i.delay, d_str, i.noexist,no_str, i.version]
		rh_table_list.append(_list)

	csvfile.create_file(join(_dir, 'tmp'), date + '.xlsx')
	excel_file = join(_dir, 'tmp', 'rh_' + date + '.xlsx')

	e = excelfile.excel_file(excel_file)
	e.main_rh_fuion(table_header, data, city_m)

	##磁带库
	data = general.objects.filter(date=filter_time, type='磁带库')

	general_table_list = []

	for i in data:
		general_table_list.append([date, i.type, i.results])

	##备注说明
	data = general.objects.filter(date=filter_time, type='备注说明')
	if data:
		note = data[0].note

	if 'mail_select' in request.GET:
		##数据源
		gps_list = []
		for i in gps_data.objects.all().filter(date=int(filter_time)):
			if i.interrupt:
				s = i.interrupt
				s = s.encode('gbk')
				if len(i.interrupt) > 25:  ##中断大于25字符，截取
					_interrupt = ','.join(s.split(',')[0:2]) + ' 等'
				else:
					_interrupt = s
				gps_list.append(
					{'source': i.source, 'cars': i.cars, 'gps_data': i.gps_data, 'repeats': '%.2f' % (i.repeats),
					 'interrupt': _interrupt})

		##磁带库
		if general_table_list:
			cidai_status = general_table_list[0][2]
		else:
			cidai_status = ""



		# 15Q4预处理
		data = fusion_yc.objects.filter(date=filter_time, version='15Q4')
		r = ribao_create.ribao(data)
		_list_fusion_15q4 = r.data_create()

		# 15Q4融合
		data = rh_yc.objects.filter(date=filter_time, version='15Q4')
		r = ribao_create.ribao(data)
		_list_rh_15q4 = r.data_create()

		# 16Q2预处理
		data = fusion_yc.objects.filter(date=filter_time, version='16Q2')
		r = ribao_create.ribao(data)
		_list_fusion_16q2 = r.data_create()

		# 16Q2融合
		data = rh_yc.objects.filter(date=filter_time, version='16Q2')
		r = ribao_create.ribao(data)
		_list_rh_16q2 = r.data_create()
		##邮件发送

		mail_send.send_html_mail('掌行通监控日报', {'date': date, "gps_list": gps_list, "list_fusion_15q4": _list_fusion_15q4,
											 "list_rh_15q4": _list_rh_15q4, \
											 "list_fusion_16q2": _list_fusion_16q2, "list_rh_16q2": _list_rh_16q2,
											 'cidai_status': cidai_status, 'note': note}, \
								 ['taojun@chinatransinfo.com','monitor@palmcity.cn'])

	return render_to_response('ribao.html', {'note': note, 'date': date, 'table_header': table_header,
											 'fusion_table_list': fusion_table_list, \
											 'rh_table_list': rh_table_list, 'general_table_list': general_table_list,
											 'table_general': table_general, \
											 'rhfilename': 'rh_' + date + '.xlsx',
											 'fusionfilename': 'fusion_' + date + '.xlsx',\
											 'perms':list(request.user.get_all_permissions())})


def ribao_backend(request):  ##在网页中打开前一天 日报的html

	## http://192.168.100.4:8000/ribao_backend/?date=2016-08-20   任意日期

	date = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60))

	d = datetime.datetime.strptime(date, "%Y-%m-%d")
	filter_time = time.mktime(d.timetuple())  ##默认昨天

	table_header = [u'服务器IP', u'城市', u'延迟数', u'延迟时间段', u'不存在个数', u'不存在时间段', u'版本']
	table_general = [u'日期', u'类型', u'结果']

	if 'date' in request.GET:
		date = request.GET['date']
		d = datetime.datetime.strptime(date, "%Y-%m-%d")
		filter_time = time.mktime(d.timetuple())

	##数据源
	gps_list = []
	for i in gps_data.objects.all().filter(date=int(filter_time)):
		if i.interrupt:
			s = i.interrupt
			s = s.encode('gbk')
			if len(i.interrupt) > 25:  ##中断大于25字符，截取
				_interrupt = ','.join(s.split(',')[0:2]) + ' 等'
			else:
				_interrupt = s
			gps_list.append(
				{'source': i.source, 'cars': i.cars, 'gps_data': i.gps_data, 'repeats': '%.2f' % (i.repeats),
				 'interrupt': _interrupt})

	##磁带库
	cidai_status = ''
	data = general.objects.filter(date=filter_time, type='磁带库')
	if data:
		general_table_list = []
		for i in data:
			general_table_list.append([date, i.type, i.results])
		cidai_status = general_table_list[0][2]

	note = ""
	data = general.objects.filter(date=filter_time, type='备注说明')
	if data:
		note = data[0].note

	# 15Q4预处理
	data = fusion_yc.objects.filter(date=filter_time, version='15Q4')
	r = ribao_create.ribao(data)
	_list_fusion_15q4 = r.data_create()

	# 15Q4融合
	data = rh_yc.objects.filter(date=filter_time, version='15Q4')
	r = ribao_create.ribao(data)
	_list_rh_15q4 = r.data_create()

	# 16Q2预处理
	data = fusion_yc.objects.filter(date=filter_time, version='16Q2')
	r = ribao_create.ribao(data)
	_list_fusion_16q2 = r.data_create()

	# 16Q2融合
	data = rh_yc.objects.filter(date=filter_time, version='16Q2')
	r = ribao_create.ribao(data)
	_list_rh_16q2 = r.data_create()

	# print note
	return render_to_response('mail_template.html',
							  {'date': date, "list_fusion_15q4": _list_fusion_15q4, "list_rh_15q4": _list_rh_15q4,
							   "gps_list": gps_list, \
							   "list_fusion_16q2": _list_fusion_16q2, "list_rh_16q2": _list_rh_16q2,
							   'cidai_status': cidai_status, 'note': note})


from settings import ribao_mails
def ribao_mailsend(request):  ##日报 发现前一天邮件
	date = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60))

	d = datetime.datetime.strptime(date, "%Y-%m-%d")
	filter_time = time.mktime(d.timetuple())  ##默认昨天

	##数据源
	gps_list = []
	for i in gps_data.objects.all().filter(date=int(filter_time)):
		if i.interrupt:
			s = i.interrupt
			s = s.encode('gbk')
			if len(i.interrupt) > 25:  ##中断大于25字符，截取
				_interrupt = ','.join(s.split(',')[0:2]) + ' 等'
			else:
				_interrupt = s
			gps_list.append(
				{'source': i.source, 'cars': i.cars, 'gps_data': i.gps_data, 'repeats': '%.2f' % (i.repeats),
				 'interrupt': _interrupt})

	##磁带库
	cidai_status = ''
	data = general.objects.filter(date=filter_time, type='磁带库')
	if data:
		general_table_list = []
		for i in data:
			general_table_list.append([date, i.type, i.results])
		cidai_status = general_table_list[0][2]

	note = ""
	data = general.objects.filter(date=filter_time, type='备注说明')
	if data:
		note = data[0].note

	# 15Q4预处理
	data = fusion_yc.objects.filter(date=filter_time, version='15Q4')
	r = ribao_create.ribao(data)
	_list_fusion_15q4 = r.data_create()

	# 15Q4融合
	data = rh_yc.objects.filter(date=filter_time, version='15Q4')
	r = ribao_create.ribao(data)
	_list_rh_15q4 = r.data_create()

	# 16Q2预处理
	data = fusion_yc.objects.filter(date=filter_time, version='16Q2')
	r = ribao_create.ribao(data)
	_list_fusion_16q2 = r.data_create()

	# 16Q2融合
	data = rh_yc.objects.filter(date=filter_time, version='16Q2')
	r = ribao_create.ribao(data)
	_list_rh_16q2 = r.data_create()

	##收件人
	ribao_mail_sendto=ribao_mails

	#print ribao_mail_sendto
	##邮件发送
	log.info('Module:view.ribao_mailsend 成功发送邮件,邮件日期:%s' % (date))
	mail_send.send_html_mail('掌行通监控日报', {'date': date, "gps_list": gps_list, "list_fusion_15q4": _list_fusion_15q4,
										 "list_rh_15q4": _list_rh_15q4, \
										 "list_fusion_16q2": _list_fusion_16q2, "list_rh_16q2": _list_rh_16q2,
										 'cidai_status': cidai_status, 'note': note}, \
							 ribao_mail_sendto)




import fault_totla_output

@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.monitor_total')
def fault_total(request):
	fault = fault_totla_output.fault_total_output()
	_type_list = fault.type_list_return()  ##页面中类型列表

	_list = []
	for i in _type_list:  ##加入 select
		_list.append({'type': i, 'select': ''})
	_type_list = _list

	startdate = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60 * 7))  ##一周前

	enddate = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60))

	if 'scope' in request.GET and 'type' in request.GET:
		date_range = request.GET['scope']

		date_range = str(date_range)

		startdate, enddate = date_range.split(' ')[0], date_range.split(' ')[-1]

		type_str = request.GET['type']
		for n in xrange(len(_type_list)):
			i = _type_list[n]
			if i['type'] == type_str:  ##是否在页面上选择过
				_type_list[n]['select'] = "selected="

		if 'month_select' in request.GET:  ##是否点中 月报
			data_list, excelfile = fault.main(startdate, enddate, type_str, month=1)
			checked = "checked="
		else:
			data_list, excelfile = fault.main(startdate, enddate, type_str)
			checked = ""

		field = ["类型", "城市", "日期", "故障开始时间", "故障结束时间", "中断时间", "故障原因"]
		# print startdate,data_list
		return render_to_response('fault_total.html',
								  {'type_list': _type_list, 'startdate': startdate, 'enddate': enddate,
								   'type_str': type_str, \
								   'table_header': field, 'data_list': data_list, 'excelfilename': excelfile, \
								   'excelfile': basename(excelfile), 'checked': checked,'perms':list(request.user.get_all_permissions())})
	else:
		return render_to_response('fault_total.html',
								  {'type_list': _type_list, 'startdate': startdate, 'enddate': enddate,'perms':list(request.user.get_all_permissions())})




from palmgo.models import restart

@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.monitor_total')
def total_restart(request):

	rs = redis_data.redis_data()

	startdate = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60 * 7))  ##一周前

	enddate = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60))

	filed = ['日期', '城市', '程序', '版本']
	select_16q2 = ""
	select_15q4 = ''
	select_dti = ''
	if 'version' in request.GET and 'scope' in request.GET:
		date_range = request.GET['scope']
		date_range = str(date_range)
		startdate, enddate = date_range.split(' ')[0], date_range.split(' ')[-1]

		version = request.GET['version']

		if version == '16Q2':
			select_16q2 = "selected="

		elif version == '15Q4':
			select_15q4 = "selected="

		else:
			select_dti = "selected="

		start = datetime.datetime.strptime(startdate, "%Y-%m-%d")
		end = datetime.datetime.strptime(enddate, "%Y-%m-%d")

		start = time.mktime(start.timetuple())
		end = time.mktime(end.timetuple()) + 86400

		fault = fault_totla_output.fault_total_output()  ##生成日期序列
		date_list = fault.init_datelist(int(end), int(start))

		date_list = map(lambda x: time.strftime("%Y-%m-%d", time.localtime(x)), date_list)
		data = []
		for i in restart.objects.filter(date__range=(start, end), version=version):
			data.append([time.strftime("%Y-%m-%d", time.localtime(i.date)), city_m[i.citycode], i.program,
						 i.version])  ##形成数据表的 城市名


	else:
		return render_to_response('total_restart.html',
								  {'table_header': filed, 'startdate': startdate, 'enddate': enddate,\
								   'perms':list(request.user.get_all_permissions())})

	return render_to_response('total_restart.html', {'table_header': filed, 'startdate': startdate, 'enddate': enddate, \
													 'data': data, 'select_15q4': select_15q4,
													 'select_16q2': select_16q2, 'select_dti': select_dti,\
													 'perms':list(request.user.get_all_permissions())})

@login_required(login_url=settings.LOGIN_URL)
@permission_required('palmgo.event_total')
def event_inter_show(request):

	s = mysql_data.session(db='siwei15Q4rtti')
	inter_event_data=s.event_inter_data()

	inter_event_list=[]
	nn=0
	for i in inter_event_data:
		n= str(i[0].split(';')[1]).split(",")
		# print i[3],type(i[3])
		# inter_event_list.append([n[0],n[1],str(u"start time: "+i[1])+"</br>"+str(u"end time: "+i[2]) \
		# 						 +"</br>"+i[3]])
		# inter_event_list.append({"lng":n[0],"lat":n[1],"remark":str(u"开始时间: "+i[1])+"</br>"+str(u"结束时间: "+i[2]) +"</br>" \
		# 						+ u"内容: "+i[3]})
		# print str(i[3]).strip(),i[4]

		m=i[3].strip().replace(" ","").replace("\n","").replace("\r","")
		# print str(nn)+i[3]
		print  str(nn)+m
		nn=nn+1
		inter_event_list.append({"lng":n[0],"lat":n[1],"remark":u"开始时间:"+str(i[1])+"</br>"+u"结束时间:"+str(i[2])+"</br>"+u"内容:"+m})
		# inter_event_list.append({"lng":n[0],"lat":n[1],"remark":u"内容:"+i[3].strip().replace(" ","")})
		# inter_event_list.append({"lng":n[0],"lat":n[1],"remark":u'内容:'+m})
		# inter_event_list.append({"lng":116.417854,"lat":39.921988,"remark":'123'+"</br>"+'456'})
		# inter_event_list.append([n[0],n[1], '在'+"</br>"+'456'])

	# inter_event_list=[{"lng":116.417854,"lat":39.921988,"remark":'123'+"</br>"+'456'}]
	# print inter_event_list[0]
	return render_to_response("event_inter_show.html",{'inter_event_list':inter_event_list,'perms':list(request.user.get_all_permissions())})


import traceback
from django.http.response import HttpResponse
from weixin_main import weixin_main
from weixin_main import send_message
# from zabbix_restart import zabbix_restart
def weixin(request):
	if request.method == 'GET':
		signature = request.GET['msg_signature']
		timestamp = request.GET['timestamp']
		nonce = request.GET['nonce']
		echostr = request.GET['echostr']
		wx = weixin_main()
		sEchoStr = 0
		sEchoStr = wx.check_signature(signature=signature, timestamp=timestamp, nonce=nonce, echostr=echostr)
		return HttpResponse(sEchoStr, content_type="text/plain")

	signature = request.REQUEST.get('msg_signature')
	timestamp = request.REQUEST.get('timestamp')
	nonce = request.REQUEST.get('nonce')
	##POST方法传递过来的

	wx = weixin_main()
	type, xml_tree = wx.Decrypt(request.body, signature, timestamp, nonce)  ##把请求POST过来的 解密

	msg = None
	print 'type:' + type
	if type == 'event':  ##点击菜单事件
		eventkey = xml_tree.find("EventKey").text
		if eventkey == "monitor_ribao":  ##日报 回复  NEW
			msg = wx.Encrypt_new(title='掌行通监控日报', url='http://yw.palmgo.com.cn:8885/ribao_backend',
								 picurl='http://yw.palmgo.com.cn:8885/bootstrap/tmp/ribao.png')

	if type == 'text':  ##发送接收 文字
		content = xml_tree.find('Content').text
		print content
		if content == '1':  ##判断文字内容
			msg = wx.Encrypt_text('测试' + '/:rose' + '/:P-(')  ##回复文字

	if type == 'event':  ##点击菜单事件
		eventkey = xml_tree.find("EventKey").text
		log.info('Module:view.weixin 方法:%s' % (eventkey))
		fromusername = xml_tree.find('FromUserName').text
		if eventkey == "weizhi":  ##位置,与 企业号 自带的位置功能，返回的XML不同
			try:
				lable = xml_tree.find('SendLocationInfo').find('Label').text
				x = xml_tree.find('SendLocationInfo').find('Location_X').text
				y = xml_tree.find('SendLocationInfo').find('Location_Y').text
				fromusername = xml_tree.find('FromUserName').text
				log.info('Module:view.weixin 微信客户:%s' % (fromusername))
				#print u'客户:' + fromusername
				lable = lable.encode('utf-8')
				send_m = send_message()  ##不能直接回复文字， 利用主动发送信息
				send_m.send_data('位置:' + str(lable) + '\n' + '经度:' + str(x) + '\n' + '纬度:' + str(y), fromusername)
			except Exception as e:
				print traceback.print_exc()
				print str(e)
		if eventkey == "restart20.1":
			try:
				i=zabbix_restart('172.16.20.1')

				log.info("restart20.1")
				if i:
					message="sucess restart 172.16.20.1 kafaka"
				else:
					message="sucess restart 172.16.20.1 kafaka"
				send_m=send_message()
				send_m.send_data(message,fromusername)
				log.info(message)

			except Exception as e:
				print traceback.print_exc()
				log.info( str(e))

		if eventkey == "restart20.3":
			try:
				i=zabbix_restart('172.16.20.3')

				log.info("restart20.3")
				if i:
					message="sucess restart 172.16.20.3 kafaka"
				else:
					message="sucess restart 172.16.20.3 kafaka"
				send_m=send_message()
				send_m.send_data(message,fromusername)
				log.info(message)

			except Exception as e:
				print traceback.print_exc()
				log.info(str(e))

	return HttpResponse(msg, content_type="application/xml")


from weixin_main import sdk
from palmgo.settings import corpid


def weixin_sdk(request):
	print request.REQUEST
	url = 'http://' + request.get_host() + request.path  ##动态获取当前页面
	print url
	s = sdk()
	timestamp = int(time.time())
	ret = s.get_signature(timestamp, url)

	return render_to_response("weixin_sdk.html", {'corpid': corpid, 'timestamp': timestamp, 'nonceStr': ret['nonceStr'],
												  'signature': ret['signature']})


from zabbix_alerts_data import zabbix_alerts_data


def zabbix_alerts(request):
	z = zabbix_alerts_data()
	_list, _list_event = z.select_alerts()
	_list_qf,_list_event_qf=z.select_alerts_qf()

	field = ["知悉", "主机", "报警名称", "起始时间"]

	print request.GET
	if 'zhixi' in request.GET:

		for i in request.GET:
			if i in _list_event:
				z.update_alerts(i)
			if i in _list_event_qf:
				z.update_alerts_qf(i)

		_list, _list_event = z.select_alerts()
		_list_qf,_list_event_qf=z.select_alerts_qf()

	# print _list_event_qf
	# print _list_event
	if 'all-zhixi' in request.GET:
		if _list_event:
			z.all_update_alerts()
		if _list_event_qf:
			z.all_update_alerts_qf()

		_list, _list_event = z.select_alerts()
		_list_qf,_list_event_qf = z.select_alerts_qf()

	_list=_list+_list_qf
	del _list_event_qf
	del _list_event

	return render_to_response("zabbix_alerts.html",
							  {'table_header': field, 'table_list': _list, 'len_list': len(_list)})

# def form_components(request):
# 	if 'note' in request.GET:
# 		print request.GET['note']
# 	return render_to_response("form_components.html")
def help(request):

	return render_to_response("help.htm")